package com.yafeed.trade.service.industry.impl;

import com.alibaba.fastjson.JSONObject;
import com.yafeed.trade.common.http.HttpUtils;
import com.yafeed.trade.component.SinaUrl;
import com.yafeed.trade.dao.IndustryMapper;
import com.yafeed.trade.dao.LeaderStockMapper;
import com.yafeed.trade.pojo.dto.industry.IndustryDto;
import com.yafeed.trade.service.industry.IndustryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @description: 板块信息
 * @author: yanghj
 * @time: 2020-12-13 14:47
 */

@Service
public class IndustryServiceImpl implements IndustryService {

    @Resource
    private IndustryMapper industryMapper;

    @Resource
    private LeaderStockMapper leaderStockMapper;

    /**
     * http 工具
     */
    private HttpUtils httpUtils;

    /**
     * 新浪接口地址
     */
    private SinaUrl sinaUrl;

    /**
     * @return list
     */
    @Override
    public List<IndustryDto> fetchSinaIndustries() {
        String industryStr = httpUtils.get(sinaUrl.getIndustry(), String.class);
        String[] split = industryStr.split("=");
        JSONObject jsonObject = JSONObject.parseObject(split[1]);
        List<IndustryDto> industryDtos = new ArrayList<>();
        Set<Map.Entry<String, Object>> entries = jsonObject.entrySet();
        for (Map.Entry<String, Object> entry : entries) {
            String serNo = entry.getValue().toString();
            IndustryDto industryDto = IndustryDto.of(serNo);
            industryDtos.add(industryDto);
        }
        return industryDtos;
    }

    /*
     * <pre>
     *     保存行业信息
     * </pre>
     * @param industryDtos
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveSinaIndustry(List<IndustryDto> industryDtos) {
        for (IndustryDto industryDto : industryDtos) {
            industryMapper.insertSelective(industryDto.toIndustry());
        }
    }

    /*
     * <pre>
     *     保存领涨股
     * </pre>
     * @param industryDtos
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveSinaLeaderStock(List<IndustryDto> industryDtos) {
        for (IndustryDto industryDto : industryDtos) {
            leaderStockMapper.insertSelective(industryDto.getLeaderStockDto().toLeaderStock());
        }
    }


    @Autowired
    public void setHttpUtils(HttpUtils httpUtils) {
        this.httpUtils = httpUtils;
    }

    @Autowired
    public void setSinaUrl(SinaUrl sinaUrl) {
        this.sinaUrl = sinaUrl;
    }
}
